#include <stdio.h>
#include <stdint.h>

#define  	__linux__			1


#if __linux__
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <pthread.h>
#include <sys/types.h>

#include <unistd.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include "errno.h"
#endif

#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include <semaphore.h>

//#include "hdmi.h"
#include "vdma.h"
#include "printf.h"
#include "video_ps.h"

#include "serial_usb.h"
#include "usb_udp.h"
#include "make_time.h"
#include "usb_v4l2.h"

#if 1

int _kbhit(long tv_sec, long tv_usec)
{
	struct timeval tv;
	fd_set rdfs;

	tv.tv_sec = tv_sec;
	tv.tv_usec = tv_usec;

	FD_ZERO(&rdfs);
	FD_SET(STDIN_FILENO, &rdfs);

	select(STDIN_FILENO + 1, &rdfs, NULL, NULL, &tv);
	//select(STDIN_FILENO + 1, &rdfs, NULL, NULL, NULL);

	return FD_ISSET(STDIN_FILENO, &rdfs);
}


int block_scankey(void)
{
	// ���ռ�������;
	bool iskey = _kbhit(0, 0);
	if (iskey)
	{
		char ch = getchar();
		putchar(ch);
		ch = tolower(ch);
		if (ch == 'q' || ch == 'Q')   // �˳�
		{
			return -1;
		}
	}
	return 0;
}

int noblock_scankey(void)
{
	// ���ռ�������;
	bool iskey = _kbhit(0, 60000);
	if (iskey)
	{
		char ch = getchar();
		putchar(ch);
		ch = tolower(ch);
		if (ch == 'q' || ch == 'Q')   // �˳�
		{
			return -1;
		}
	}
	return 0;
}



int main(int argc, char* argv[])
{
	int ret;

	char Version[] = "Version: V0.10" ;
	char Date[] =  __DATE__ ;
	unsigned char * yuv_buffer_pointer;
	unsigned int len;


	printf("-------------------------------------------------------\n");
	printf("main() ... %s, %s\n", Version, Date);
	printf("-------------------------------------------------------\n");

	//	������ 01.bmp
	if (argc > 1)  
	{
		//------------------------------------------------
		//  ��ȡbmp�ļ�
		//------------------------------------------------
//		static unsigned short yuvData[CAM_HSIZE * CAM_VSIZE];
		static unsigned char yuvData[CAM_HSIZE * CAM_VSIZE*CAM_PIXELLENGTH];
	    static char * yuv_buffer_pointer_tmp;
	    static unsigned int len_tmp;
//		static unsigned char* rgbData = NULL;
//		if (rgbData == NULL)
//		{
//			rgbData	= clLoadImage(argv[1]);
//			rgb2yuv422Packed(rgbData, /*out*/ yuvData);
//			printf("open(%s) ok\n", argv[1]);
//		}

		usb_camera_initial();
		while(1)
		{
//			with8to16((void **)&yuv_buffer_pointer,&len,yuvData);
			get_frame(yuvData);
//			data_convert(yuv_buffer_pointer_tmp,yuvData);
			// usb������ʾ����
			memcpy2usb(/*frame,*/ yuvData, CAM_HSIZE * CAM_VSIZE * CAM_PIXELLENGTH);
			usb_show_yuv422();
			free_frame();
			//usleep(60*1000);
			if (noblock_scankey() < 0) 
				goto lb_exit;
		}
	}
	// ��������
	else 
	{
		//hdmi_init();
		ret = vdma_init();
		if (ret < 0)
		{
			dbg_error("vdma_init() error\n");
			return -1;
		}
		
		while(1)
		{
			if (block_scankey() < 0) 
				goto lb_exit;
		}
	}

	// �˳�
lb_exit:
	vdma_halt();
	//hdmi_uninit();
	exit(0);
}



#endif




